package cc.git.liuyan.customeraiagent.core.bigmodel.abstrct;

import cc.git.liuyan.customeraiagent.core.bigmodel.BigModelApiClient;
import cc.git.liuyan.customeraiagent.core.json.Json;
import okhttp3.OkHttpClient;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSources;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

public abstract class AbstractBigModelApiClient<Api> implements BigModelApiClient<Api> {
    private final boolean logStreamingResponses;
    private final OkHttpClient okHttpClient;
    private EventSource.Factory eventSourceFactory;
    private final Api giteeAiEmbeddingApi;

    public AbstractBigModelApiClient(AbstractBigModelProviderInfo providerInfo, Class<Api> apiClass) {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder().callTimeout(providerInfo.getApiCallTimeout()).connectTimeout(providerInfo.getApiConnectTimeout()).readTimeout(providerInfo.getApiReadTimeout()).writeTimeout(providerInfo.getApiWriteTimeout());
        if (providerInfo.getApiDispatcher() != null) {
            okHttpClientBuilder.dispatcher(providerInfo.getApiDispatcher());
        }
        if (providerInfo.getApiInterceptors() != null) {
            providerInfo.getApiInterceptors().forEach(interceptor -> okHttpClientBuilder.addInterceptor(interceptor));
        }
        if (providerInfo.getApiProxy() != null) {
            okHttpClientBuilder.proxy(providerInfo.getApiProxy());
        }
        this.logStreamingResponses = providerInfo.getLogStreamingResponses();
        this.okHttpClient = okHttpClientBuilder.build();
        this.eventSourceFactory = EventSources.createFactory(this.okHttpClient);
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder().baseUrl(providerInfo.getBaseUrl()).client(this.okHttpClient);
        retrofitBuilder.addConverterFactory(JacksonConverterFactory.create(Json.OBJECT_MAPPER));
        this.giteeAiEmbeddingApi = retrofitBuilder.build().create(apiClass);
    }

    @Override
    public final Api getApi() {
        return this.giteeAiEmbeddingApi;
    }

    @Override
    public final EventSource.Factory getEventSourceFactory() {
        return this.eventSourceFactory;
    }

    @Override
    public final boolean getIfLogStreamingResponses() {
        return this.logStreamingResponses;
    }
}
